package com.shujia;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2;
import org.apache.hadoop.hbase.mapreduce.KeyValueSortReducer;
import org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles;
import org.apache.hadoop.hbase.mapreduce.SimpleTotalOrderPartitioner;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Demo8BulkLoading {
    public static class BulkMapper extends Mapper<LongWritable, Text, ImmutableBytesWritable, KeyValue> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, ImmutableBytesWritable, KeyValue>.Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split(",");
            String mdn = split[0];
            String start_date = split[1];
            String lg = split[4];
            String lat = split[5];
            byte[] rowkey = (mdn + "_" + start_date).getBytes();

            // KeyValue对象 相当于一个Cell
            KeyValue lgV = new KeyValue(rowkey, "cf1".getBytes(), "lg".getBytes(), lg.getBytes());
            KeyValue latV = new KeyValue(rowkey, "cf1".getBytes(), "lat".getBytes(), lat.getBytes());

            context.write(new ImmutableBytesWritable(rowkey), lgV);
            context.write(new ImmutableBytesWritable(rowkey), latV);

        }
    }

    // Driver
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set("hbase.zookeeper.quorum", "master,node1,node2");
        Job job = Job.getInstance(conf);
        job.setJobName("Demo8BulkLoading");
        job.setJarByClass(Demo8BulkLoading.class);

        // 配置Map端
        job.setMapperClass(BulkMapper.class);
        job.setMapOutputKeyClass(ImmutableBytesWritable.class);
        job.setMapOutputValueClass(KeyValue.class);

        // 保证每个Reduce是有序的
        job.setPartitionerClass(SimpleTotalOrderPartitioner.class);
        // 配置Reduce端
        // KeyValueSortReducer 只能保证每个Reduce里处理的数据有序
        job.setReducerClass(KeyValueSortReducer.class);
        // 该配置在这里是无效的
        // Reduce数量由表的Region的数量决定
//        job.setNumReduceTasks(5);
        // 配置输入输出路径
        FileInputFormat.addInputPath(job, new Path("/data/dianxin/"));
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(new Path("/bulk/"))) {
            fs.delete(new Path("/bulk/"), true);
        }
        FileOutputFormat.setOutputPath(job, new Path("/bulk/"));
        Connection conn = ConnectionFactory.createConnection(conf);
        Admin admin = conn.getAdmin();
        Table bulk_load = conn.getTable(TableName.valueOf("bulk_load"));
        // 用于获取表的Region的信息
        RegionLocator bulk_load_region_locator = conn.getRegionLocator(TableName.valueOf("bulk_load"));
        // 将Reduce的输出格式化成Hfile 以待进行bulkloading
        HFileOutputFormat2.configureIncrementalLoad(job, bulk_load, bulk_load_region_locator);



        // 等待job运行完成
        boolean flag = job.waitForCompletion(true);

        if (flag) {
            System.out.println("MR运行成功");
            // 使用LoadIncrementalHFiles将生成的HFile加载到HBase对应的表中
            LoadIncrementalHFiles load = new LoadIncrementalHFiles(conf);
            load.doBulkLoad(new Path("/bulk/"), admin, bulk_load, bulk_load_region_locator);

        } else {
            System.out.println("MR运行失败");
        }

        /**
         * hdfs dfs -mkdir -p /data/dianxin/
         * hdfs dfs -put DIANXIN.csv /data/dianxin/
         * hadoop jar HBaseJavaAPI12-1.0-jar-with-dependencies.jar com.shujia.Demo8BulkLoading
         */
    }
}
